package com.ktjy.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ktjy.crm.mapper.RightMapper;
import com.ktjy.crm.mapper.RoleMapper;
import com.ktjy.crm.model.Right;
import com.ktjy.crm.model.Role;
import com.ktjy.crm.service.RightService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
@Service("rightService")
public class RightServiceImpl  implements RightService {
    @Resource
    private RightMapper rightMapper;
    @Resource
    private RoleMapper roleMapper;
    @Override
    public int insert(Right right) {
        try{
            return rightMapper.insert(right);
        }catch (Exception e){
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int delete(String id) {
        try {
            QueryWrapper<Right> wrapper = new QueryWrapper<Right>();
            wrapper.eq("right_code",id);
            return rightMapper.delete(wrapper);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int update(Right right) {
        try{
            return rightMapper.updateById(right);
        }catch (Exception e){
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public Right get(String id) {
        try {
            LambdaQueryWrapper<Right> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Right::getRightCode, id);
            return rightMapper.selectOne(wrapper);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public List<Right> findAll() {
        try{
            return rightMapper.selectList(null);
        }catch (Exception e){
            e.printStackTrace();
        }
        return List.of();
    }
    @Override
    public Role getRoleWithRights(Long roleId) {
        // 获取角色基本信息
        Role role = roleMapper.selectById(roleId);
        if (role != null) {
            // 获取角色权限
            List<Right> rights = (List<Right>) rightMapper.selectRightsByRoleId(roleId);
            role.setRights(rights);
        }
        return role;
    }
}
